#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/7/11 10:33
# @Author  : 胡浩浩
# @File    : zentao_tools.py
# @IDE     : PyCharm
# @description :
import os.path
import random
import time
from hashlib import md5

import requests

from lxml import etree, html
from pywebio.pin import pin_update

from apps.commons.json_tools import read_json_file


class ZenTaoTools:
    def __init__(self):
        self.session = requests.session()
        self.host = "http://192.168.75.98"
        # todo： 需要建一个定时任务去拉取禅道中的用例文件
        test_sheet_data_path = "data/test_sheet_data.json"

        self.zen_tao_url = []

        test_sheet_data_json = read_json_file(test_sheet_data_path)
        for key, value in test_sheet_data_json.items():
            self.zen_tao_url.append({
                "product": f"{value[0]}",
                "desc": f"{value[1]}",
                "url": f"{value[3]}",
            })

    def data_md5(self, data):
        return md5(data.encode("utf-8")).hexdigest()

    def get_zentaosid(self):
        login_page = self.session.get(self.host + "/zentao/user-login.html")
        print(login_page.headers)
        login_page.encoding = 'utf-8'
        SID = login_page.cookies['zentaosid']
        print('SID = ' + SID)
        cookies = {
            'zentaosid': f'{SID}',
        }
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Referer': 'http://192.168.75.98/zentao/user-login.html',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
        }
        verifyRand = self.session.get(self.host + "/zentao/user-refreshRandom.html", cookies=cookies, headers=headers,
                                      verify=False).text
        print(verifyRand)
        return SID, verifyRand

    def login(self):
        zentaosid, verifyRand = self.get_zentaosid()
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': f'zentaosid={zentaosid}',
            'Origin': 'http://192.168.75.98',
            'Referer': 'http://192.168.75.98/zentao/user-login.html',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }
        print(verifyRand)
        password = self.data_md5(self.data_md5("1q2w3e!Q@W#E") + verifyRand)
        print(password)
        data = {
            'account': 'hu_haohao',
            'password': password,
            'passwordStrength': '0',
            'referer': '/zentao/',
            'verifyRand': verifyRand,
            'keepLogin': '1',
            'captcha': '',
        }
        response = self.session.post('http://192.168.75.98/zentao/user-login.html', headers=headers, data=data,
                                     verify=False)
        print(response.text)
        del headers["Content-Type"]
        self.session.headers = headers
        print(self.session.headers)

    def get_all_case_url_data(self, url):
        """
            获取所有测试用例的链接
        """
        response = self.session.get(self.host + url, verify=False)

        # print(response)
        response.encoding = "utf-8"
        tree = etree.HTML(response.text)
        # print(self.host + url)
        # print(response.text)
        href_list = tree.xpath('//*[@id="caseList"]/tbody/tr/td[2]/a/@href')
        print(href_list)
        return href_list

    def get_case_detail(self, url):
        """
            获取测试用例的详情中附件的地址
            http://192.168.75.98/zentao/testcase-view-18171-2-testtask-1131.html
        """
        response = self.session.get(
            self.host + url,
            verify=False,
        )
        # print(response.text)
        response.encoding = "utf-8"
        tree = etree.HTML(response.text)
        href_list = tree.xpath('//*[@id="mainContent"]/div[1]/div[1]/div/div[2]/ul/li/a/@href')
        # href_list = tree.xpath('//*[@id="mainContent"]/div[1]/div[1]/div[3]/div[2]/ul/li/a')
        filename_list = tree.xpath('//*[@id="mainContent"]/div[1]/div[1]/div/div[2]/ul/li/a/text()')
        # print(href_list)
        # print(filename_list)
        for i in range(len(filename_list)):
            filename_list[i] = filename_list[i][2:-1]
        # print(filename_list)
        result = {}
        for key, value in zip(filename_list, href_list):
            result[key] = value
        print(result)
        return result

    def get_file_download(self, path, key, value, show_data_str):
        response = self.session.get(
            self.host + value,
            verify=False,
        )
        # print(response.content)
        with open(f"{path}/{key}", mode="wb") as f:
            f.write(response.content)
        print(f"{key}测试用例存储完成")
        show_data_str = f"{key}测试用例存储完成\n" + show_data_str
        pin_update("show_data", value=show_data_str)

    def get_file_download_job(self, path, key, value):
        response = self.session.get(
            self.host + value,
            verify=False,
        )
        # print(response.content)
        with open(f"{path}/{key}", mode="wb") as f:
            f.write(response.content)
        print(f"{key}测试用例存储完成")

    def run(self, url, item_path, show_data_str):
        self.login()
        print("444")
        for case_url in self.get_all_case_url_data(url):
            print(case_url)
            for key, value in self.get_case_detail(case_url).items():
                print(key)
                print(value)
                if key in os.listdir(item_path):
                    print(os.listdir(item_path))
                    print("我已经下载过了")
                    show_data_str = f"{time.strftime('%Y-%m-%d %H:%M:%S：')}我已经下载过了{key}\n" + show_data_str
                    pin_update("show_data", value=show_data_str)

                else:
                    if ".yml" in key or ".yaml" in key:
                        self.get_file_download(item_path, key, value, show_data_str)

        return show_data_str

    def run_job(self, url, item_path):
        self.login()
        print("444")
        for case_url in self.get_all_case_url_data(url):
            print(case_url)
            for key, value in self.get_case_detail(case_url).items():
                print(key)
                print(value)
                if key in os.listdir(item_path):
                    print(os.listdir(item_path))
                    print("我已经下载过了")

                else:
                    if ".yml" in key or ".yaml" in key:
                        self.get_file_download_job(item_path, key, value)


if __name__ == '__main__':
    zt = ZenTaoTools()
    zt.login()
